<template>
  <div class="message" :class="{ 'user-message': isUser, 'bot-message': !isUser }">
    <!-- 头像部分 -->
    <div class="message-avatar">
      <div :class="isUser ? 'user-avatar' : 'bot-avatar'">
        {{ isUser ? '用户' : 'AI' }}
      </div>
    </div>

    <!-- 消息内容部分 -->
    <div class="message-content">
      <!-- 消息操作按钮（悬停时显示） -->
      <div class="message-actions">
        <button 
          v-if="isUser" 
          @click="handleEdit" 
          class="action-btn edit-btn" 
          title="编辑消息"
        >
          ✏️ 编辑
        </button>
        <button 
          v-if="!isUser" 
          @click="handleCopy" 
          class="action-btn copy-btn" 
          title="复制回答"
        >
          📋 复制
        </button>
      </div>

      <!-- AI消息的工作流模式布局（整合） -->
      <div v-if="!isUser && metadata && metadata.use_workflow" class="workflow-container">
        <!-- 工作流信息卡片（顶部） -->
        <div class="workflow-info">
          <div class="workflow-header">
            <div class="workflow-title-group">
              <span class="workflow-icon">⚙️</span>
              <span class="workflow-title">工作流模式分析</span>
            </div>
            <span class="workflow-badge">{{ metadata.workflow_steps }} 步骤</span>
          </div>
          <div v-if="metadata.tools_used && metadata.tools_used.length > 0" class="tools-used">
            <span class="tools-label">使用的工具:</span>
            <div class="tools-list">
              <span
                v-for="(tool, index) in metadata.tools_used"
                :key="index"
                class="tool-badge"
              >
                {{ getToolDisplayName(tool) }}
              </span>
            </div>
          </div>
        </div>

        <!-- 思维链可视化（可折叠） -->
        <WorkflowChain
          v-if="metadata.tool_calls"
          :tool-calls="metadata.tool_calls"
          :retrieved-logs-count="metadata.retrieved_logs_count || 0"
          class="workflow-chain-section"
        />

        <!-- AI回答内容 -->
        <div class="message-text workflow-answer" v-html="renderMarkdown(content)"></div>
      </div>

      <!-- 普通AI消息（非工作流模式） -->
      <div v-else-if="!isUser" class="message-text" v-html="renderMarkdown(content)"></div>

      <!-- 用户消息：纯文本 -->
      <div v-if="isUser" class="message-text plain-text">{{ content }}</div>

      <!-- 时间 -->
      <div class="message-time">{{ formatTime(timestamp) }}</div>
    </div>
  </div>
</template>

<script setup>
import MarkdownIt from 'markdown-it'
import hljs from 'highlight.js'
import DOMPurify from 'dompurify'
import 'highlight.js/styles/github.css'
import WorkflowChain from './WorkflowChain.vue'

const props = defineProps({
  isUser: Boolean,
  content: String,
  timestamp: String,
  messageId: Number,
  metadata: {
    type: Object,
    default: null
  }
})

const emits = defineEmits(['edit', 'copy'])

// 工具名称显示映射
function getToolDisplayName(toolName) {
  const toolNames = {
    'analyze_error_frequency': '错误频率分析',
    'detect_anomalies': '异常检测',
    'extract_key_metrics': '关键指标提取',
    'analyze_trends': '趋势分析',
    'search_pattern': '模式搜索',
    'compare_logs': '日志对比',
    'generate_summary': '综合摘要',
    'analyze_time_patterns': '时间模式分析',
    'detect_slow_requests': '慢请求检测',
    'detect_security_issues': '安全问题检测',
    'statistical_analysis': '统计分析'
  }
  return toolNames[toolName] || toolName
}

// 初始化 Markdown 渲染器
const md = new MarkdownIt({
  html: true,
  linkify: true,
  typographer: true,
  highlight: function (str, lang) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return '<pre class="hljs"><code>' +
          hljs.highlight(str, { language: lang }).value +
          '</code></pre>'
      } catch (__) {}
    }
    return '<pre class="hljs"><code>' +
      md.utils.escapeHtml(str) +
      '</code></pre>'
  },
})

// 渲染 Markdown + 安全过滤
function renderMarkdown(raw) {
  if (!raw) return ''
  const html = md.render(String(raw))
  return DOMPurify.sanitize(html)
}

// 格式化时间（带日期）
function formatTime(ts) {
  if (!ts) return ''
  try {
    const d = new Date(ts)
    const date = d.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
    })
    const time = d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
    return `${date} ${time}`
  } catch {
    return ts
  }
}

// 显示复制成功提示
function showCopySuccess() {
  // 创建一个临时的提示元素
  const toast = document.createElement('div')
  toast.textContent = '✓ 已复制到剪贴板'
  toast.style.cssText = `
    position: fixed;
    top: 20px;
    right: 20px;
    background: #4facfe;
    color: white;
    padding: 12px 20px;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(79, 172, 254, 0.3);
    z-index: 10000;
    font-size: 14px;
    animation: fadeInOut 2s ease-in-out;
  `
  
  // 添加动画
  const style = document.createElement('style')
  style.textContent = `
    @keyframes fadeInOut {
      0% { opacity: 0; transform: translateY(-10px); }
      20% { opacity: 1; transform: translateY(0); }
      80% { opacity: 1; transform: translateY(0); }
      100% { opacity: 0; transform: translateY(-10px); }
    }
  `
  document.head.appendChild(style)
  document.body.appendChild(toast)
  
  // 2秒后移除
  setTimeout(() => {
    toast.remove()
    style.remove()
  }, 2000)
}

// 复制内容到剪贴板
function copyToClipboard(text) {
  if (navigator.clipboard && window.isSecureContext) {
    navigator.clipboard.writeText(text).then(() => {
      showCopySuccess()
    }).catch(err => {
      console.error('复制失败:', err)
      fallbackCopy(text)
      showCopySuccess()
    })
  } else {
    fallbackCopy(text)
    showCopySuccess()
  }
}

// 备用复制方法
function fallbackCopy(text) {
  const textArea = document.createElement('textarea')
  textArea.value = text
  textArea.style.position = 'fixed'
  textArea.style.opacity = '0'
  document.body.appendChild(textArea)
  textArea.select()
  try {
    document.execCommand('copy')
    console.log('已复制到剪贴板')
  } catch (err) {
    console.error('复制失败:', err)
  }
  document.body.removeChild(textArea)
}

// 处理复制
function handleCopy() {
  copyToClipboard(props.content)
  emits('copy')
}

// 处理编辑
function handleEdit() {
  emits('edit', props.messageId, props.content)
}
</script>

<style scoped>
/* 整体布局 */
.message {
  display: flex;
  align-items: flex-start;
  margin: 16px 0;
  padding: 0 16px;
  animation: fadeIn 0.3s ease-in;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 用户消息反向排列（右侧） */
.user-message {
  flex-direction: row-reverse;
}

/* 头像样式 */
.message-avatar {
  flex-shrink: 0;
  width: 44px;
  height: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: bold;
  color: #fff;
  margin: 0 12px;
}

/* 用户头像*/
.user-avatar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  width: 44px;
  height: 44px;
  border-radius: 50%;
  display: flex;
  align-items: center;     
  justify-content: center; 
  line-height: 1;          
  text-align: center;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
  font-size: 0.9rem;
  font-weight: 600;
}

/* AI 头像*/
.bot-avatar {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  width: 44px;
  height: 44px;
  border-radius: 50%;
  display: flex;
  align-items: center;     
  justify-content: center; 
  line-height: 1;          
  text-align: center;
  box-shadow: 0 4px 12px rgba(79, 172, 254, 0.4);
  font-size: 0.9rem;
  font-weight: 600;
}

/* 内容气泡 */
.message-content {
  max-width: 75%;
  min-width: 200px;
  display: flex;
  flex-direction: column;
  margin: 0 8px;
  position: relative;
}

/* 消息操作按钮 */
.message-actions {
  position: absolute;
  top: -8px;
  right: 0;
  display: flex;
  gap: 6px;
  opacity: 0;
  transition: opacity 0.2s ease;
  z-index: 10;
}

.message:hover .message-actions {
  opacity: 1;
}

.action-btn {
  background: white;
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: 6px;
  padding: 4px 10px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.2s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  color: #666;
}

.action-btn:hover {
  background: #f0f0f0;
  border-color: rgba(79, 172, 254, 0.5);
  color: #4facfe;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.edit-btn:hover {
  color: #667eea;
  border-color: rgba(102, 126, 234, 0.5);
}

.copy-btn:hover {
  color: #4facfe;
  border-color: rgba(79, 172, 254, 0.5);
}

/* 工作流容器 - 整合布局 */
.workflow-container {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

/* 工作流信息卡片 */
.workflow-info {
  background: linear-gradient(135deg, #f0f7ff 0%, #e6f3ff 100%);
  border: 1px solid rgba(79, 172, 254, 0.3);
  border-radius: 12px;
  padding: 14px 16px;
  box-shadow: 0 2px 8px rgba(79, 172, 254, 0.15);
}

.workflow-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
  margin-bottom: 8px;
}

.workflow-title-group {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
}

.workflow-icon {
  font-size: 18px;
}

.workflow-title {
  font-weight: 600;
  color: #2c3e50;
  font-size: 14px;
  flex: 1;
}

.workflow-badge {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: white;
  padding: 2px 10px;
  border-radius: 12px;
  font-size: 11px;
  font-weight: 600;
  box-shadow: 0 2px 4px rgba(79, 172, 254, 0.3);
}

.tools-used {
  display: flex;
  flex-direction: column;
  gap: 6px;
  margin-top: 8px;
  padding-top: 8px;
  border-top: 1px solid rgba(79, 172, 254, 0.2);
}

.tools-label {
  font-size: 12px;
  color: #666;
  font-weight: 500;
}

.tools-list {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.tool-badge {
  background: white;
  color: #4facfe;
  padding: 4px 10px;
  border-radius: 12px;
  font-size: 11px;
  font-weight: 500;
  border: 1px solid rgba(79, 172, 254, 0.3);
  transition: all 0.2s ease;
}

.tool-badge:hover {
  background: #4facfe;
  color: white;
  transform: translateY(-1px);
  box-shadow: 0 2px 6px rgba(79, 172, 254, 0.3);
}

/* 气泡样式 */
.message-text {
  padding: 16px 20px;
  border-radius: 16px;
  line-height: 1.7;
  word-break: break-word;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
  white-space: normal;
  transition: all 0.3s ease;
}

/* 用户气泡（右侧渐变蓝紫） */
.user-message .message-text {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  align-self: flex-end;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.25);
}

.user-message .message-text code {
  background: rgba(255, 255, 255, 0.2);
  color: rgba(255, 255, 255, 0.95);
}

.user-message .message-text a {
  color: rgba(255, 255, 255, 0.9);
  border-bottom-color: rgba(255, 255, 255, 0.5);
}

.user-message .message-text a:hover {
  color: white;
}

/* AI 气泡（白色卡片，带阴影） */
.bot-message .message-text {
  background: white;
  color: #2c3e50;
  border: 1px solid rgba(0, 0, 0, 0.08);
  align-self: flex-start;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.bot-message .message-text:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
}

/* 工作流模式下的回答样式 */
.workflow-answer {
  margin-top: 0;
  background: white;
  border-top: 1px solid rgba(79, 172, 254, 0.15);
  border-radius: 0 0 16px 16px;
  padding: 16px 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

/* 思维链组件样式 */
.workflow-chain-section {
  margin: 0;
  border-radius: 12px;
  overflow: hidden;
}

/* 确保工作流容器的统一样式 */
.workflow-container .message-text {
  border-radius: 0;
  box-shadow: none;
}

.workflow-container .workflow-info {
  border-radius: 12px 12px 0 0;
}

.workflow-container .workflow-answer {
  border-radius: 0 0 16px 16px;
}

/* ====== 时间样式 ====== */
.message-time {
  font-size: 11px;
  color: #999;
  margin-top: 8px;
  text-align: right;
  font-style: italic;
  padding: 0 4px;
}

.user-message .message-time {
  text-align: left;
}

/* Markdown 样式优化 */
.message-text {
  color: #2c3e50;
  font-size: 15px;
  line-height: 1.8;
}

.message-text p {
  margin: 10px 0;
  line-height: 1.8;
}

.message-text h1,
.message-text h2,
.message-text h3,
.message-text h4,
.message-text h5,
.message-text h6 {
  margin: 20px 0 12px 0;
  color: #1a1a1a;
  font-weight: 700;
  line-height: 1.4;
}

.message-text h1 {
  font-size: 1.8em;
  border-bottom: 3px solid rgba(79, 172, 254, 0.3);
  padding-bottom: 10px;
  margin-top: 24px;
}

.message-text h2 {
  font-size: 1.5em;
  border-bottom: 2px solid rgba(79, 172, 254, 0.2);
  padding-bottom: 8px;
  margin-top: 20px;
}

.message-text h3 {
  font-size: 1.25em;
  margin-top: 16px;
}

.message-text h4 {
  font-size: 1.1em;
  margin-top: 14px;
}

/* 列表样式 - 确保正确的缩进和层级 */
/* 使用 :deep() 确保样式应用到渲染后的 HTML */
.message-text :deep(ul),
.message-text :deep(ol) {
  margin: 12px 0 12px 0 !important;
  padding-left: 36px !important;
  line-height: 1.9;
  list-style-position: outside;
}

.message-text :deep(li) {
  margin: 6px 0;
  line-height: 1.8;
  padding-left: 0;
  list-style-position: outside;
  display: list-item;
}

.message-text :deep(li > p) {
  margin: 4px 0;
}

/* 嵌套列表样式 */
.message-text :deep(li ul),
.message-text :deep(li ol) {
  margin: 8px 0;
  padding-left: 28px;
}

/* 确保列表项的项目符号在内容外侧 */
.message-text :deep(ul) {
  list-style-type: disc;
}

.message-text :deep(ol) {
  list-style-type: decimal;
}

/* 标题后的列表 - 使用通用兄弟选择器，覆盖可能存在的段落 */
.message-text :deep(h1 ~ ul),
.message-text :deep(h1 ~ ol),
.message-text :deep(h1 + ul),
.message-text :deep(h1 + ol),
.message-text :deep(h2 ~ ul),
.message-text :deep(h2 ~ ol),
.message-text :deep(h2 + ul),
.message-text :deep(h2 + ol),
.message-text :deep(h3 ~ ul),
.message-text :deep(h3 ~ ol),
.message-text :deep(h3 + ul),
.message-text :deep(h3 + ol),
.message-text :deep(h4 ~ ul),
.message-text :deep(h4 ~ ol),
.message-text :deep(h4 + ul),
.message-text :deep(h4 + ol),
.message-text :deep(h5 ~ ul),
.message-text :deep(h5 ~ ol),
.message-text :deep(h5 + ul),
.message-text :deep(h5 + ol),
.message-text :deep(h6 ~ ul),
.message-text :deep(h6 ~ ol),
.message-text :deep(h6 + ul),
.message-text :deep(h6 + ol) {
  margin-left: 20px !important;
  margin-top: 8px;
  padding-left: 36px !important;
}

/* 段落后的列表 */
.message-text :deep(p + ul),
.message-text :deep(p + ol) {
  margin-top: 8px;
}

/* 确保所有顶级列表都有足够的缩进 */
.message-text > :deep(ul),
.message-text > :deep(ol) {
  margin-left: 0;
  padding-left: 36px !important;
}

/* 代码块样式 */
.message-text pre.hljs {
  background: #1e1e1e;
  color: #d4d4d4;
  padding: 16px 18px;
  border-radius: 10px;
  overflow-x: auto;
  margin: 16px 0;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
  border: 1px solid rgba(0, 0, 0, 0.1);
  font-size: 14px;
  line-height: 1.6;
}

.message-text pre.hljs::-webkit-scrollbar {
  height: 8px;
}

.message-text pre.hljs::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 4px;
}

.message-text pre.hljs::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.2);
  border-radius: 4px;
}

.message-text pre.hljs::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.3);
}

/* 行内代码样式 */
.message-text code {
  font-family: "Fira Code", "SF Mono", "Monaco", "Consolas", "Liberation Mono", "Courier New", monospace;
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.12) 0%, rgba(79, 172, 254, 0.12) 100%);
  color: #667eea;
  padding: 3px 7px;
  border-radius: 5px;
  font-size: 0.88em;
  font-weight: 500;
  border: 1px solid rgba(102, 126, 234, 0.15);
}

.bot-message .message-text code {
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.12) 0%, rgba(79, 172, 254, 0.12) 100%);
  color: #667eea;
}

.message-text pre code {
  background: transparent;
  color: inherit;
  padding: 0;
  border: none;
  font-size: inherit;
}

/* 引用块样式 */
.message-text blockquote {
  border-left: 4px solid #4facfe;
  padding: 12px 18px;
  margin: 16px 0;
  background: linear-gradient(90deg, rgba(79, 172, 254, 0.05) 0%, rgba(79, 172, 254, 0.02) 100%);
  color: #555;
  font-style: italic;
  border-radius: 0 6px 6px 0;
}

.message-text blockquote p {
  margin: 4px 0;
}

/* 链接样式 */
.message-text a {
  color: #4facfe;
  text-decoration: none;
  border-bottom: 1.5px solid rgba(79, 172, 254, 0.3);
  transition: all 0.2s ease;
  font-weight: 500;
}

.message-text a:hover {
  border-bottom-color: #4facfe;
  color: #00f2fe;
  background: rgba(79, 172, 254, 0.05);
  padding: 2px 4px;
  margin: 0 -4px;
  border-radius: 4px;
}

/* 表格样式 */
.message-text table {
  width: 100%;
  border-collapse: collapse;
  margin: 16px 0;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid rgba(79, 172, 254, 0.15);
}

.message-text table th,
.message-text table td {
  border: 1px solid rgba(79, 172, 254, 0.15);
  padding: 12px 14px;
  text-align: left;
}

.message-text table th {
  background: linear-gradient(135deg, rgba(79, 172, 254, 0.15) 0%, rgba(79, 172, 254, 0.08) 100%);
  font-weight: 700;
  color: #2c3e50;
  text-transform: uppercase;
  font-size: 0.85em;
  letter-spacing: 0.5px;
}

.message-text table tr:nth-child(even) {
  background: rgba(79, 172, 254, 0.03);
}

.message-text table tr:hover {
  background: rgba(79, 172, 254, 0.08);
}

/* 水平分割线 */
.message-text hr {
  border: none;
  border-top: 2px solid rgba(79, 172, 254, 0.2);
  margin: 20px 0;
  border-radius: 2px;
}

/* 强调文本 */
.message-text strong {
  color: #1a1a1a;
  font-weight: 700;
}

.message-text em {
  font-style: italic;
  color: #555;
}

/* 图片样式 */
.message-text img {
  max-width: 100%;
  height: auto;
  border-radius: 8px;
  margin: 16px 0;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
</style>
